package com.techsoul.module.basic.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.basic.mapper.CustomerMapper;
import com.techsoul.module.basic.mapper.StoreBrandRelMapper;
import com.techsoul.module.basic.mapper.StoreMapper;
import com.techsoul.module.basic.mapper.SupplierMapper;
import com.techsoul.module.basic.pojo.entity.Store;
import com.techsoul.module.basic.pojo.entity.StoreBrandRel;
import com.techsoul.module.basic.pojo.param.StoreBrandRelSaveParam;
import com.techsoul.module.basic.pojo.param.StoreSaveParam;
import com.techsoul.module.basic.pojo.param.StoreSearchParam;
import com.techsoul.module.basic.pojo.vo.CustomerVo;
import com.techsoul.module.basic.pojo.vo.StoreBrandRelVo;
import com.techsoul.module.basic.pojo.vo.StoreVo;
import com.techsoul.module.basic.pojo.vo.SupplierVo;
import com.techsoul.module.basic.service.IStoreService;
import com.techsoul.module.goods.mapper.BrandMapper;
import com.techsoul.module.goods.pojo.entity.Brand;
import com.techsoul.module.pms.mapper.GoodsSupplierMapper;
import com.techsoul.module.goods.mapper.SkuMapper;
import com.techsoul.module.pms.pojo.entity.GoodsSupplier;
import com.techsoul.module.goods.pojo.entity.Sku;
import com.techsoul.module.pms.pojo.param.GoodsSupplierSaveParam;
import com.techsoul.module.pms.pojo.vo.GoodsSupplierVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 店铺 Service实现
 *
 * @author liuen
 * @date 2021-05-02
 */
@Service
@Transactional(readOnly = true)
public class StoreServiceImpl implements IStoreService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private StoreMapper mapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private StoreBrandRelMapper storeBrandRelMapper;
    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private GoodsSupplierMapper goodsSupplierMapper;

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(StoreSaveParam params,UserVo user) {

        Store entity = new Store();
        BeanUtils.copyProperties(params, entity);
        if(user.getSite()!=null&&user.getSite()!=""){
            entity.setSite(user.getSite());
        }else{
            entity.setSite(user.getOrgId());
        }
        entity.setIsValid("1");
        List<String> brandnames = new ArrayList<String>();
        if(!StringUtils.isNull(entity.getMallId())){
            CustomerVo cust = customerMapper.findById(entity.getMallId());
            entity.setMallName(cust.getCustomerName());
        }
        if(!StringUtils.isNull(entity.getSupplierId())){
            SupplierVo supplier = supplierMapper.findById(entity.getSupplierId());
            entity.setSupplierName(supplier.getSupplierName());
        }
        entity.setId(idWorker.nextId() + "").preInsert(user.getId());

        if(params.getBrandList()!=null&&params.getBrandList().size()>0){
             for(int i =0; i < params.getBrandList().size();i++){
                StoreBrandRelSaveParam storeBrandRelSaveParam
                        = (StoreBrandRelSaveParam)params.getBrandList().get(i);
                 if(brandnames.contains(storeBrandRelSaveParam.getBrandName())){
                      continue;
                 }else{
                     brandnames.add(storeBrandRelSaveParam.getBrandName());
                 }
                if(StringUtils.isNull(storeBrandRelSaveParam.getBrandId())||storeBrandRelSaveParam.getBrandId().equals(""))
                {
                    // 品牌没有建立
                    Brand brand = this.brandMapper.findByCode(storeBrandRelSaveParam.getBrandCode());
                    if(brand==null){
                        brand = new Brand();
                        brand.setBrandCode(storeBrandRelSaveParam.getBrandCode());
                        brand.setBrandName(storeBrandRelSaveParam.getBrandName());
                        brand.setId(idWorker.nextId() + "").preInsert(user.getId());
                        this.brandMapper.insert(brand);
                    }

                    storeBrandRelSaveParam.setBrandCode(storeBrandRelSaveParam.getBrandCode());
                    storeBrandRelSaveParam.setBrandName(brand.getBrandName()) ;
                    storeBrandRelSaveParam.setBrandId(brand.getId());
                    storeBrandRelSaveParam.setStoreId(entity.getId());
                    storeBrandRelSaveParam.setStoreName(entity.getStoreName());
                    StoreBrandRel storeBrandRel = new StoreBrandRel();
                    BeanUtils.copyProperties(storeBrandRelSaveParam, storeBrandRel);
                    storeBrandRel.setId(idWorker.nextId() + "").preInsert(user.getId());
                    storeBrandRel.setIsValid("1");
                    storeBrandRelMapper.insert(storeBrandRel);

                }else{
                    storeBrandRelSaveParam.setBrandCode(storeBrandRelSaveParam.getBrandCode());
                    storeBrandRelSaveParam.setBrandName(storeBrandRelSaveParam.getBrandName()) ;
                    storeBrandRelSaveParam.setBrandId(storeBrandRelSaveParam.getBrandId());
                    storeBrandRelSaveParam.setStoreId(entity.getId());
                    storeBrandRelSaveParam.setStoreName(entity.getStoreName());
                    StoreBrandRel storeBrandRel = new StoreBrandRel();
                    BeanUtils.copyProperties(storeBrandRelSaveParam, storeBrandRel);
                    storeBrandRel.setId(idWorker.nextId() + "").preInsert(user.getId());
                    storeBrandRel.setIsValid("1");
                    storeBrandRelMapper.insert(storeBrandRel);
                }

            } // end for

        } // end list null
        if(params.getGoodsList()!=null&&params.getGoodsList().size()>0){
            for(int i =0; i < params.getGoodsList().size();i++){
                GoodsSupplierSaveParam storeBrandRelSaveParam
                        = (GoodsSupplierSaveParam)params.getGoodsList().get(i);
                if(StringUtils.isNull(storeBrandRelSaveParam.getSkuId())||storeBrandRelSaveParam.getSkuId().equals(""))
                {
                    // SKU没有建立
                    Sku brand = new Sku();
                    brand.setBrandId(storeBrandRelSaveParam.getBrandId());
                    brand.setBrandName(storeBrandRelSaveParam.getBrandName());
                    brand.setSpec(storeBrandRelSaveParam.getSpec());
                    brand.setSkuName(storeBrandRelSaveParam.getSkuName());
                    brand.setSn(storeBrandRelSaveParam.getSn());
                    brand.setId(idWorker.nextId() + "").preInsert(user.getId());
                    this.skuMapper.insert(brand);
                    storeBrandRelSaveParam.setBrandId(storeBrandRelSaveParam.getBrandId());
                    storeBrandRelSaveParam.setBrandName(brand.getBrandName()) ;
                    storeBrandRelSaveParam.setBrandId(brand.getId());
                    storeBrandRelSaveParam.setSupplierId(entity.getSupplierId());
                    storeBrandRelSaveParam.setSupplierName(entity.getSupplierName());
                    storeBrandRelSaveParam.setSkuName(brand.getSkuName());
                    storeBrandRelSaveParam.setStoreId(entity.getId());
                    storeBrandRelSaveParam.setStoreName(entity.getStoreName());
                    GoodsSupplier storeBrandRel = new GoodsSupplier();
                    BeanUtils.copyProperties(storeBrandRelSaveParam, storeBrandRel);
                    storeBrandRel.setId(idWorker.nextId() + "").preInsert(user.getId());
                    storeBrandRel.setIsValid("1");
                    goodsSupplierMapper.insert(storeBrandRel);

                }else{
                    storeBrandRelSaveParam.setBrandId(storeBrandRelSaveParam.getBrandId());
                    storeBrandRelSaveParam.setBrandName(storeBrandRelSaveParam.getBrandName()) ;
                    storeBrandRelSaveParam.setBrandId(storeBrandRelSaveParam.getBrandId());
                    storeBrandRelSaveParam.setStoreId(entity.getId());
                    storeBrandRelSaveParam.setStoreName(entity.getStoreName());
                    storeBrandRelSaveParam.setSupplierId(entity.getSupplierId());
                    storeBrandRelSaveParam.setSupplierName(entity.getSupplierName());
                    GoodsSupplier storeBrandRel = new GoodsSupplier();
                    BeanUtils.copyProperties(storeBrandRelSaveParam, storeBrandRel);
                    storeBrandRel.setId(idWorker.nextId() + "").preInsert(user.getId());
                    storeBrandRel.setIsValid("1");
                    goodsSupplierMapper.insert(storeBrandRel);
                }

            } // end for

        } // end list null
        this.mapper.insert(entity);
        return entity.getId();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 批量作废
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer logicalDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            for(int i=0;i<idList.size();i++){
                String id = (String)idList.get(i);
                Store entityFromDb = this.mapper.selectById(id);

                UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

                entityFromDb.preUpdate(user.getId());
                entityFromDb.setIsValid("0");
                this.mapper.updateById(entityFromDb);
            }
            return 1;
        } else {
            return 0;
        }
    }
    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(StoreSaveParam params) {
        Store entityFromDb = this.mapper.selectById(params.getId());
        StoreVo storeVo = this.mapper.findById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(user.getId());
        List<String> brandnames = new ArrayList<String>();
        if(!StringUtils.isNull(entityFromDb.getMallId())){
            CustomerVo cust = customerMapper.findById(entityFromDb.getMallId());
            entityFromDb.setMallName(cust.getCustomerName());
        }
        if(!StringUtils.isNull(entityFromDb.getSupplierId())){
            SupplierVo supplier = supplierMapper.findById(entityFromDb.getSupplierId());
            entityFromDb.setSupplierName(supplier.getSupplierName());
        }
        if(storeVo.getBrandList()!=null&&storeVo.getBrandList().size()>0){
            for (int i = 0; i < storeVo.getBrandList().size(); i++) {
                StoreBrandRelVo storeBrandRelSaveParam
                        = (StoreBrandRelVo) storeVo.getBrandList().get(i);
                storeBrandRelMapper.deleteById(storeBrandRelSaveParam.getId());
            }
        }
        if(params.getBrandList()!=null&&params.getBrandList().size()>0) {
            for (int i = 0; i < params.getBrandList().size(); i++) {
                StoreBrandRelSaveParam storeBrandRelSaveParam
                        = (StoreBrandRelSaveParam) params.getBrandList().get(i);
                if(brandnames.contains(storeBrandRelSaveParam.getBrandName())){
                    continue;
                }else{
                    brandnames.add(storeBrandRelSaveParam.getBrandName());
                }

                if (StringUtils.isNull(storeBrandRelSaveParam.getBrandId()) || storeBrandRelSaveParam.getBrandId().equals("")) {
                    // 品牌没有建立
                    Brand brand = new Brand();
                    brand.setBrandCode(storeBrandRelSaveParam.getBrandCode());
                    brand.setBrandName(storeBrandRelSaveParam.getBrandName());
                    brand.setId(idWorker.nextId() + "").preInsert(user.getId());
                    this.brandMapper.insert(brand);
                    storeBrandRelSaveParam.setBrandCode(storeBrandRelSaveParam.getBrandCode());
                    storeBrandRelSaveParam.setBrandName(brand.getBrandName());
                    storeBrandRelSaveParam.setBrandId(brand.getId());
                    storeBrandRelSaveParam.setStoreId(entityFromDb.getId());
                    storeBrandRelSaveParam.setStoreName(entityFromDb.getStoreName());
                    StoreBrandRel storeBrandRel = new StoreBrandRel();
                    BeanUtils.copyProperties(storeBrandRelSaveParam, storeBrandRel);
                    storeBrandRel.setId(idWorker.nextId() + "").preInsert(user.getId());
                    storeBrandRel.setIsValid("1");
                    storeBrandRelMapper.insert(storeBrandRel);

                } else {
                    storeBrandRelSaveParam.setBrandCode(storeBrandRelSaveParam.getBrandCode());
                    storeBrandRelSaveParam.setBrandName(storeBrandRelSaveParam.getBrandName());
                    storeBrandRelSaveParam.setBrandId(storeBrandRelSaveParam.getBrandId());
                    storeBrandRelSaveParam.setStoreId(entityFromDb.getId());
                    storeBrandRelSaveParam.setStoreName(entityFromDb.getStoreName());
                    StoreBrandRel storeBrandRel = new StoreBrandRel();
                    BeanUtils.copyProperties(storeBrandRelSaveParam, storeBrandRel);
                    storeBrandRel.setId(idWorker.nextId() + "").preInsert(user.getId());
                    storeBrandRel.setIsValid("1");
                    storeBrandRelMapper.insert(storeBrandRel);
                }

            } // end for
        }
        if(storeVo.getGoodsList()!=null&&storeVo.getGoodsList().size()>0){
            for (int i = 0; i < storeVo.getGoodsList().size(); i++) {
                GoodsSupplierVo storeBrandRelSaveParam
                        = (GoodsSupplierVo) storeVo.getGoodsList().get(i);
                goodsSupplierMapper.deleteById(storeBrandRelSaveParam.getId());
            }
        }
        if(params.getGoodsList()!=null&&params.getGoodsList().size()>0) {
            for(int i =0; i < params.getGoodsList().size();i++){
                GoodsSupplierSaveParam storeBrandRelSaveParam
                        = (GoodsSupplierSaveParam)params.getGoodsList().get(i);
                if(StringUtils.isNull(storeBrandRelSaveParam.getSkuId())||storeBrandRelSaveParam.getSkuId().equals(""))
                {
                    // SKU没有建立
                    Sku brand = new Sku();
                    brand.setBrandId(storeBrandRelSaveParam.getBrandId());
                    brand.setBrandName(storeBrandRelSaveParam.getBrandName());
                    brand.setSpec(storeBrandRelSaveParam.getSpec());
                    brand.setSkuName(storeBrandRelSaveParam.getSkuName());
                    brand.setSn(storeBrandRelSaveParam.getSn());
                    brand.setId(idWorker.nextId() + "").preInsert(user.getId());
                    this.skuMapper.insert(brand);
                    storeBrandRelSaveParam.setBrandId(storeBrandRelSaveParam.getBrandId());
                    storeBrandRelSaveParam.setBrandName(brand.getBrandName()) ;
                    storeBrandRelSaveParam.setBrandId(brand.getId());
                    storeBrandRelSaveParam.setSupplierId(storeVo.getSupplierId());
                    storeBrandRelSaveParam.setSupplierName(storeVo.getSupplierName());
                    storeBrandRelSaveParam.setSkuName(brand.getSkuName());
                    storeBrandRelSaveParam.setStoreId(storeVo.getId());
                    storeBrandRelSaveParam.setStoreName(storeVo.getStoreName());
                    GoodsSupplier storeBrandRel = new GoodsSupplier();
                    BeanUtils.copyProperties(storeBrandRelSaveParam, storeBrandRel);
                    storeBrandRel.setId(idWorker.nextId() + "").preInsert(user.getId());
                    storeBrandRel.setIsValid("1");
                    goodsSupplierMapper.insert(storeBrandRel);

                }else{
                    storeBrandRelSaveParam.setBrandId(storeBrandRelSaveParam.getBrandId());
                    storeBrandRelSaveParam.setBrandName(storeBrandRelSaveParam.getBrandName()) ;
                    storeBrandRelSaveParam.setBrandId(storeBrandRelSaveParam.getBrandId());
                    storeBrandRelSaveParam.setStoreId(storeVo.getId());
                    storeBrandRelSaveParam.setStoreName(storeVo.getStoreName());
                    storeBrandRelSaveParam.setSupplierId(storeVo.getSupplierId());
                    storeBrandRelSaveParam.setSupplierName(storeVo.getSupplierName());
                    GoodsSupplier storeBrandRel = new GoodsSupplier();
                    BeanUtils.copyProperties(storeBrandRelSaveParam, storeBrandRel);
                    storeBrandRel.setId(idWorker.nextId() + "").preInsert(user.getId());
                    storeBrandRel.setIsValid("1");
                    goodsSupplierMapper.insert(storeBrandRel);
                }

            } // end for
        }
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public StoreVo findById(String id) {
        return this.mapper.findById(id);
    }
    /**
     * 通过名称查询
     * @param storename
     * @return
     */
    @Override
    public StoreVo findByName(String storename) {
        return this.mapper.findByName(storename);
    }

    /**
     * 通过编码查询
     * @param code
     * @return
     */
    @Override
    public StoreVo findByCode(String code) {
        return this.mapper.findByCode(code);
    }
    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<StoreVo> findAll(StoreSearchParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        if(user.getSite()!=null&&user.getSite()!=""){
            params.setSite(user.getSite());
        }else{
            params.setSite(user.getOrgId());
        }
        List<StoreVo> rtlist =this.mapper.findAll(params);
        return rtlist;
    }

    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<StoreVo> findAll(StoreSearchParam params, Integer current, Integer pageSize) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        if(user.getSite()!=null&&user.getSite()!=""){
            params.setSite(user.getSite());
        }else{
            params.setSite(user.getOrgId());
        }
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }

    /**
     * 校验店铺编码
     * @param params
     * @return
     */
    @Override
    public Boolean checkStoreCode(StoreSearchParam params) {
        StoreVo storeVo = this.findByCode(params.getStoreCode());
        if (storeVo == null) {
            return true;
        } else {
            if (storeVo.getId().equals(params.getId())) {
                return true;
            } else {
                return false;
            }
        }
    }

}
